package com.yupi.springbootinit.bizmq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.listener.ExcelListener;
import com.yupi.springbootinit.manager.AIManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class BIMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private AIManager aiManager;

    //指定@RabbitListener()注解，会自动填充参数，死记硬背即可
    @RabbitListener(queues = {BIMqConstant.BI_QUEUE_NAME},ackMode = "MANUAL")
    public void recuiveMessage(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {

        if(StringUtils.isAnyBlank(message)){
            //如果更新失败，拒绝当前消息，让消息重新进入队列
            channel.basicNack(deliveryTag,false,false)  ;
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = null;
        try {
            map = objectMapper.readValue(message, Map.class);
        } catch (JsonProcessingException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"序列化消费者消息失败");
        }

        Long id = Long.valueOf((Integer) map.get("id"));
        File file = new File((String) map.get("file"));

        if(file==null){
            channel.basicNack(deliveryTag,false,false)  ;
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件为空");
        }
        Chart chart = chartService.getById(id);
        //异步读取不到文件，采取同步读取的方式
        // 将ExcelListener从ExcelUtils.excelToCsv（）方法中提取出来，这里需要用到excelListener对象存储的数组
        ExcelListener excelListener = new ExcelListener();//监听器类，用来提取监听到的数据与表头
        String csvData = ExcelUtils.excelToCsv(file, excelListener);

        Long chartId = chart.getId();

        //修改任务状态为执行中
        Chart updateChart = new Chart();
        updateChart.setId(chartId);
        //todo 建议定义状态为枚举
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag,false,false)  ;
            chartService.handleChartUpdate(chartId,"更新图表状态失败", file,chart.getUserId());
            return;
        }


        //调用接口

        //生成提问语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("你是一个数据分析师，接下来我会给你我的分析目标和原始数据，请告诉我分析结论。\n");
        stringBuilder.append("生成目标：" + chart.getGoal()).append("\n");
        stringBuilder.append("数据：" + csvData).append("\n");

        //调用Ai接口，返回字符串
        String biResponseStr = aiManager.sendMsgToXingHuo(true, stringBuilder.toString());
        String[] split = biResponseStr.split("'【【【【【'");
        if (split.length < 3) {
            channel.basicNack(deliveryTag,false,false)  ;
            chartService.handleChartUpdate(chartId,"AI生成错误", file,chart.getUserId());
            return;
        }
        String genChart = split[1].trim();
        String genResult = split[2].trim();
        updateChart.setStatus("succeed");
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        boolean updateResult = chartService.updateById(updateChart);
        if(!updateResult){
            channel.basicNack(deliveryTag,false,false)  ;
            chartService.handleChartUpdate(chartId,"更新图表状态失败", file,chart.getUserId());
        }

        //自定义创建一个新的表
        chartService.createDefineChartTable(chartId, excelListener);
        //插入数据
        chartService.insertDefineData(chartId, excelListener);

        //消息确认
        channel.basicAck(deliveryTag,false);
    }
}
